<?php

namespace addons\litestore\model;

use think\Db;
use think\Model;

class Litestoreadress extends Model
{

	// 表名
    protected $name = 'litestore_adress';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [];



    public function getList($user_id)
    {
        return self::all(compact('user_id'));
    }

    public function add($use_id, $data)
    {

        $listdata = $this->all(['user_id'=>$use_id]);
        foreach ($listdata as $key => $value) {
        	$value['isdefault'] = '0';
        	$value->save();
        }
        $data['country_code'] = Db::name('region_city')->where('country',$data['country'])->value('country_code');
        $data['state_code'] = Db::name('region_city')->where('country',$data['country'])->where('state',$data['state'])->value('state_code');

        // 添加收货地址
        $this->allowField(true)->save(array_merge([
            'user_id' => $use_id,
            'isdefault' => '1'
        ], $data));

        return true;
    }

    public function setdefault($use_id,$id){
    	$listdata = $this->all(['user_id'=>$use_id]);
        foreach ($listdata as $key => $value) {
        	$value['isdefault'] = '0';
        	$value->save();
        }
    	return ($this->get($id))->save(['isdefault' => '1']);
    }

   	public function del($id){
        return ($this->get($id))->delete();
    }

    public function detail($user_id, $address_id)
    {
        return self::get(compact('user_id', 'address_id'));
    }

    public function edit($data){
        $data['country_code'] = Db::name('region_city')->where('country',$data['country'])->value('country_code');
        $data['state_code'] = Db::name('region_city')->where('country',$data['country'])->where('state',$data['state'])->value('state_code');
        return $this->allowField(true)
            ->save($data);
    }

    public static function getdefault($use_id){
        $filter = [];
        $filter['isdefault'] = '1';
        $filter['user_id'] = $use_id;
        $default = self::get($filter);
        if($default){
            return $default;
        }else{
            return self::get(['user_id'=>$use_id]);
        }
    }
}
